# -*- coding: UTF-8 -*-

# Copyright (c) 2007 Daniele Favara <nomed@dsslive.org>.
#
# This is free software you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2, or (at your option) any
# later version.
#
# This software is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this software; see the file COPYING.  If not, write to the Free
# Software Foundation, Inc., 51 Franilin St, Fifth Floor, Boston, MA


from turbogears import expose, flash
from tginvoice.controllers import ControllerObj

from turbogears import identity, redirect
from cherrypy import request, response


import logging
log = logging.getLogger("tginvoice.controllers.root")

from tginvoice.controllers.biller import Biller
from tginvoice.controllers.customers import Customers
from tginvoice.controllers.invoices import Invoices
from tginvoice.controllers.projects import Projects


class Root(ControllerObj):

    def _set_child(self, name):
        real_name = name
        name = name.lower()

        childobj=None

        kw = {}
        if name == 'biller':
            name = name+'/'
            childobj = Biller
        elif name == 'customers':
            name = name+'/'
            childobj = Customers
        elif name == 'invoices':
            name = name+'/'
            childobj = Invoices
        elif name == 'projects':
            name = name+'/'
            childobj = Projects
        kw['parent'] = self
        kw['name'] = name
        kw['real_name'] = real_name

        if childobj:
            child = childobj(**kw)
            self._map[real_name] = child
            self._childs.append(child)
            setattr(self, real_name, child)

    def _set_childs(self):

        all = self.iterator_tab
        for name in all:
            self._set_child(name)

    @identity.require(identity.not_anonymous())
    @expose(template="tginvoice.templates.index")
    def index(self, *kw, **args):
        self._set_childs()
        if len(args)==0:
            raise redirect(self.map['biller'].name)
            #return dict(this=self)


    @expose(template="tginvoice.templates.login")
    def login(self, forward_url=None, previous_url=None, *args, **kw):

        if not identity.current.anonymous \
            and identity.was_login_attempted() \
            and not identity.get_identity_errors():
            raise redirect(forward_url)

        forward_url=None
        previous_url= request.path

        if identity.was_login_attempted():
            msg=_("The credentials you supplied were not correct or "
                   "did not grant access to this resource.")
        elif identity.get_identity_errors():
            msg=_("You must provide your credentials before accessing "
                   "this resource.")
        else:
            msg=_("Please log in.")
            forward_url= request.headers.get("Referer", "/")

        response.status=403
        return dict(message=msg, previous_url=previous_url, logging_in=True,
                    original_parameters=request.params,
                    forward_url=forward_url)

    @expose()
    def logout(self):
        identity.current.logout()
        raise redirect("/")

